import AccountsSession from "./accounts-session";

//
// Define AccountsDialog Class
//

const EVENT_KEY = "class.accounts.dialog";

const Event = {
  HIDDEN: `hidden${EVENT_KEY}`,
  SHOWN: `shown${EVENT_KEY}`
};

const AccountsDialog = {
  toggle: null,
  dialogTemplate: null,

  show(element, content) {
    element = $(element);
    this.toggle = element;

    element.one(Event.SHOWN, function() {
      $(this).blur();
    });

    element.one(Event.HIDDEN, function() {
      $(this).focus();
    });

    this.render(content);

    setTimeout(() => {
      $("#accountsDialog").addClass("show");
      $(document.body).css("overflow", "hidden");
      element.trigger(Event.SHOWN);
    }, 150);
  },

  render(content) {
    if (content) {
      AccountsSession.accountsDialogContent(content);
    }

    this.dialogTemplate = Blaze.render(Template.accounts_dialog, document.body);

    this._renderBg();
  },

  remove() {
    $("#accountsDialog").removeClass("show");

    setTimeout(() => {
      Blaze.remove(this.dialogTemplate);
      $(document.body).css("overflow", "visible");

      if (this.toggle) {
        this.toggle.trigger(Event.HIDDEN);
      }
    }, 150);
  },

  _renderBg() {
    let self = this;

    let dialogBgNode = document.createElement("div");
    dialogBgNode.className = "dialog-bg";
    dialogBgNode.id = "dialogBg";

    let dialogBg = $(dialogBgNode);
    dialogBg.appendTo("#accountsDialog");
    dialogBg.click(function() {
      self.remove();
    });
  }
};

export default AccountsDialog;
